package com.rongc.client.freight.business.mine.view.activity;

import android.content.Intent;
import android.view.View;

import com.android.volley.Response;
import com.android.volley.error.VolleyError;
import com.rongc.client.core.exception.RegexException;
import com.rongc.client.core.network.code.HandleCode;
import com.rongc.client.core.network.http.RequestManager;
import com.rongc.client.core.utils.ActivityUtils;
import com.rongc.client.core.utils.FileUtil;
import com.rongc.client.core.utils.ImageUtils;
import com.rongc.client.core.utils.RegexUtil;
import com.rongc.client.freight.R;
import com.rongc.client.freight.UniApplication;
import com.rongc.client.freight.base.BaseActivity;
import com.rongc.client.freight.base.model.DicsBean;
import com.rongc.client.freight.base.model.TipTemp;
import com.rongc.client.freight.base.request.result.NullResult;
import com.rongc.client.freight.base.view.activity.CarLengthActivity;
import com.rongc.client.freight.base.view.activity.CarModeActivity;
import com.rongc.client.freight.base.view.activity.MapGdActivity;
import com.rongc.client.freight.base.view.widget.CJRow.ARResponse;
import com.rongc.client.freight.base.view.widget.CJRow.CJRow;
import com.rongc.client.freight.base.view.widget.CJRow.CJRowListener;
import com.rongc.client.freight.base.view.widget.CJRow.CustomCJRowAdapter;
import com.rongc.client.freight.business.mine.buz.CarBuz;
import com.rongc.client.freight.business.mine.model.CarDic;
import com.rongc.client.freight.business.mine.request.api.CarCreateApi;
import com.rongc.client.freight.utils.UtilMethod;
import com.rongc.client.freight.utils.dic.IField;
import com.rongc.client.freight.utils.dic.impl.Field;
import com.rongc.client.freight.utils.dic.impl.Table;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by ccqx on 2017/7/1.
 */

public class CarCreateActivity extends BaseActivity implements View.OnClickListener{
    @Bind(R.id.cjrow)
    CJRow mRow;

    CustomCJRowAdapter baseAdapter;
    Table table_base;
    ARResponse response;

    private ArrayList<String> netPhotos = new ArrayList<>();
    ArrayList<String> filenames = new ArrayList<>();
    @OnClick({R.id.btn_submit})
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_submit:
                try{
                    prepare();
                    doUpload();
                }catch (RegexException e){
                    ActivityUtils.toast(e.getMessage());
                }

                break;
        }
    }

    void prepare() throws RegexException {
        if(!RegexUtil.checkNotNull(response.getValue("address"))){
            throw new RegexException("请选择地址");
        }else if(!RegexUtil.checkNotNull(response.getValue("carLength"))){
            throw new RegexException("请选择车长");
        }else if(!RegexUtil.checkNotNull(response.getValue("carModels"))){
            throw new RegexException("请选择车型");
        }else if(!RegexUtil.checkNotNull(response.getValue("plateno"))){
            throw new RegexException("请输入车牌号");
        }else if(!RegexUtil.checkNotNull(response.getValue("carLoad"))){
            throw new RegexException("请输入载重");
        }else if(netPhotos.size() != 4){
            throw new RegexException("请上传图片");
        }
    }

    private void doUpload(){
        ActivityUtils.toast("图片处理中...");
        mRow.postDelayed(new Runnable() {
            @Override
            public void run() {
                List<File> files = ImageUtils.makePaths2ImgFileList(netPhotos);
                netPhotos.clear();
                UtilMethod.showProgressDialog(CarCreateActivity.this, "正在上传...");

                CarCreateApi p = new CarCreateApi(respWorkersListener, errorListener, filenames, files,
                        new CarCreateApi.CarCreateParams(response.getData()));
                RequestManager.getInstance().call(p);

            }
        },100);
    }

    Response.Listener<NullResult> respWorkersListener = new Response.Listener<NullResult>() {

        @Override
        public void onResponse(NullResult response) {
            if (HandleCode.requestSuccess()) {
                ActivityUtils.toast(HandleCode.headerMessage);
                FileUtil.clearDir(FileUtil.getTempFile());
                finish();
            } else {
                UtilMethod.dismissProgressDialog(CarCreateActivity.this);
            }
        }
    };


    Response.ErrorListener errorListener = new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            UtilMethod.dismissProgressDialog(CarCreateActivity.this);
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK){
            switch (requestCode){
                case  CarDic.ResultType.Model_TYPE:
                    DicsBean.DicBean dataStr = (DicsBean.DicBean) data.getSerializableExtra("data");
                    baseAdapter.setFieldvalue("carModels",dataStr.getKey());
                    baseAdapter.notifyDataSetChanged();
                    break;
                case  CarDic.ResultType.Length_TYPE:
                    dataStr = (DicsBean.DicBean) data.getSerializableExtra("data");
                    baseAdapter.setFieldvalue("carLength",dataStr.getKey());
                    baseAdapter.notifyDataSetChanged();
                    break;
                case  CarDic.ResultType.PHOTO_TYPE:
                    filenames = data.getStringArrayListExtra("names");
                    netPhotos = data.getStringArrayListExtra("photos");
                    break;
                case CarDic.ResultType.ADDRESS_TYPE:
                    TipTemp result = (TipTemp) data.getSerializableExtra("data");
                    baseAdapter.setFieldvalue("address",result.getAddress());
                    baseAdapter.notifyDataSetChanged();
                    break;

            }
        }
    }

    @Override
    public void initView() {
        initToolbar(R.string.car_create_title);
    }

    @Override
    public void initData() {
        response = CarBuz.getMockBaseResponse();
        response.update("userId", UniApplication.getInstance().getUserInfo().getUserId());

        table_base = CarBuz.getCarTable(this);
        baseAdapter = new CustomCJRowAdapter(this, mRow,table_base, response);
        mRow.setAdapter(baseAdapter);
        baseAdapter.setCJRowListener(new CJRowListener() {
            @Override
            public boolean seedAction(int location, Field field, Object obj) {
                return false;
            }

            @Override
            public boolean activityAction(Field field, Object obj) {
                if("carModels".equals(field.getFieldName())){
                    ActivityUtils.startActivityForResult(CarCreateActivity.this,CarModeActivity.class, CarDic.ResultType.Model_TYPE);
                }else if("carLength".equals(field.getFieldName())){
                    ActivityUtils.startActivityForResult(CarCreateActivity.this,CarLengthActivity.class, CarDic.ResultType.Length_TYPE);
                }else if("photo".equals(field.getFieldName())){
                    ActivityUtils.startActivityForResult(CarCreateActivity.this,CarPhotoActivity.class, CarDic.ResultType.PHOTO_TYPE);
                }else if("address".equals(field.getFieldName())){
                    ActivityUtils.startActivityForResult(CarCreateActivity.this,MapGdActivity.class, CarDic.ResultType.ADDRESS_TYPE);
                }
                return true;
            }

            @Override
            public boolean popupWindowAction(final IField field, Object obj) {
                return false;
            }
        });
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_car_create;
    }
}
